package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zhou_gin_api/app/output/code"
)

func ApiReturnResultMiddle(c *gin.Context) {

	// 设置 example 变量
	c.Set("code", code.ResponseCode["SUCCESS"])
	c.Set("msg", "ok")
	c.Set("data", nil)

	c.Next()

	if http.StatusOK == c.Writer.Status() {

		tempCode := c.GetString("code")
		codeNumber := tempCode
		msg := c.GetString("msg")
		data, _ := c.Get("data")

		if msg == "" {
			msg = code.ResponseCodeMsg[codeNumber]
		}

		c.JSON(200, gin.H{
			"code": codeNumber,
			"msg":  msg,
			"data": data,
		})

	} else {

		c.JSON(c.Writer.Status(), gin.H{
			"code": code.ResponseCode["EXCEPTION_MESSAGE"],
			"msg":  http.StatusText(c.Writer.Status()),
			"data": nil,
		})
	}

}
